import {get,post,put,setTokens} from "../httpx";
import {UserApi} from "../urls";
import store from "../../store/store";


const loginByResp = (resp)=>{
  if (resp?.success) {
    let data = resp.data
    setTokens(data.tokens)
    store.commit('login',data.info)
    localStorage.setItem('info',JSON.stringify(data.info))
    if (data.isNewUser){
      store.commit('newUser')
    }
    return {success:true,info:data.info,isNewUser:data.isNewUser}
  }
  return resp
}

const loginByPassword = async (email, password) =>{
  let resp = await post(UserApi.loginByPassword,{email,password},true)
  return loginByResp(resp)
}

const getVerifyEmail = async (email) => {
  return await post(UserApi.verifyEmail,{email},true)
}

const getRank = () => get(UserApi.getMineRank)

const loginByCode = async (email,code) => {
  let resp = await post(UserApi.loginByCode,{email,code},true)
  return loginByResp(resp)
}

const getMyInfo = async ()=>{
  return await get(UserApi.getMineInfo)
}

const getUserInfo = async (email)=>{
  return await get(UserApi.getUserInfo,{email})
}

const changeUserInfo = async (info)=>{
  return await put(UserApi.changeUserInfo,info)
}

const changePassword = async (code,newPassword)=>{
  return await put(UserApi.changePassword,{code,newPassword})
}

const peReq = data=>post(UserApi.peReq,data)

const peGet = ()=>get(UserApi.peGet)

const peGetAll = ()=>get(UserApi.peGetAll)

const peApp = data => post(UserApi.peApp,data)

const getRoleName = r=>{
  if (r == 1) return '学生'
  if (r == 2) return '教师'
  if (r == 3) return '管理员'
}

export const User = {
  loginByCode,loginByPassword,getVerifyEmail,getMyInfo,getUserInfo,changeUserInfo,changePassword,getRank,peGetAll,peApp,peGet,peReq,getRoleName
}
